<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 货品管理</span>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="margin-top: 20px">
      <el-form-item label="货品名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入货品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物品种类" prop="goodsCategory">
        <el-select v-model="queryParams.goodsCategory" placeholder="请选择物品种类" clearable>
          <el-option
              v-for="dict in goods_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增货品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="55" align="center" />
      <el-table-column label="货品名称" align="center" prop="name" />
      <el-table-column label="物品种类" align="center" prop="goodsCategory"/>
      <el-table-column label="货品图片" align="center" prop="picture">
        <template #default="scope">
          <image-preview :src="scope.row.picture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="货品单价(元/吨)" align="center" prop="unitPrice" />
      <el-table-column label="货品描述" align="left" header-align="center" prop="description" width="300px"/>
      <el-table-column label="备注" align="left" header-align="center" prop="remarks" />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改冷链货品对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body @close="isCodeChange= false;">
      <el-scrollbar max-height="450px">
        <el-form ref="productRef" :model="form" :rules="rules" label-width="80px" label-position="top" style="padding-right: 10px">
          <el-row gutter="15">
            <el-col :span="12">
              <el-form-item label="货品编码" prop="code">
                <el-input v-model="form.code" placeholder="请输入货品编码" style="width: 100%" :disabled="isCodeChange"
                />
              </el-form-item>
              <el-form-item label="原产地" prop="origin">
                <el-input v-model="form.origin" placeholder="请输入原产地" />
              </el-form-item>
              <el-form-item label="保质期" prop="shelfLife">
                <el-input v-model="form.shelfLife" placeholder="请输入保质期" >
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货品名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入货品名称" />
              </el-form-item>
              <el-form-item label="物品种类" prop="goodsCategory">
                <el-select v-model="form.goodsCategory" placeholder="请选择物品种类" style="width: 240px">
                  <el-option
                      v-for="dict in goods_category"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="货品单价(元/吨)" prop="unitPrice">
                <el-input-number v-model="form.unitPrice" :precision="2" style="width: 240px">
                  <template #suffix>
                    <span>RMB</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="货品图片" prop="picture">
            <image-upload v-model="form.picture"/>
          </el-form-item>
          <el-form-item label="货品描述" prop="description">
            <el-input type="textarea" v-model="form.description" placeholder="请输入货品描述" />
          </el-form-item>
          <el-form-item label="货品规格" prop="specification">
            <el-input type="textarea" v-model="form.specification" placeholder="请输入货品规格" />
          </el-form-item>
          <el-form-item label="价格信息" prop="priceInformation">
            <el-input type="textarea" v-model="form.priceInformation" placeholder="请输入价格信息" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup >
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/purchase/rawProduct.js";
import useUserStore from "@/store/modules/user.js";
import {getSupplierByUsername} from "@/api/purchase/Supplier.js";
import {listDictDataAll} from "@/api/purchase/DictData.js";

const { proxy } = getCurrentInstance();
const { goods_category } = proxy.useDict('goods_category');

const productList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const username = ref("");
const supplier = ref({});

const rawProductList = ref([]); //货品列表
const isCodeChange = ref(false);//货品编号能否修改

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    companyName: null,
    goodsCategory: null,
  },
  rules: {
    code: [ // 新增编码的必填验证
      { required: true, message: "货品编码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "货品名称不能为空", trigger: "blur" }
    ],
    companyName: [
      { required: true, message: "供货商公司名称不能为空", trigger: "blur" }
    ],
    goodsCategory: [
      { required: true, message: "物品种类不能为空", trigger: "change" }
    ],
    description: [
      { required: true, message: "货品描述不能为空", trigger: "blur" }
    ],
    unitPrice: [
      { required: true, message: "货品单价不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function initial(){
  username.value = useUserStore().name
  if(username.value !== undefined){
    getSupplierByUsername(username.value).then(response => {
      supplier.value = response.data;
      handleQuery();
    })
  }
}

/** 查询冷链货品列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  //初始化货品列表 ->新增采购计划
  const query = {type: '货品'}
  listDictDataAll(query).then(response => {
    rawProductList.value = response.data;
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    companyName: null,
    goodsCategory: null,
    description: null,
    unitPrice: null,
    picture: null,
    specification: null,
    priceInformation: null,
    shelfLife: null,
    storageTemperature: null,
    origin: null,
    remarks: null
  };
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  if(supplier.value === undefined){
    queryParams.value.companyName = 'null';
  }else{
    queryParams.value.companyName = supplier.value.companyName;
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value = selection.map(item => item.name);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加冷链货品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProduct(_id).then(response => {
    form.value = response.data;
    open.value = true;
    isCodeChange.value = true;
    title.value = "修改冷链货品";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.companyName =
      supplier.value.companyName === undefined ? 'null' : supplier.value.companyName;
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增判断
        for(let i = 0; i < productList.value.length; i++){
          if(productList.value[i].code === form.value.code){
            proxy.$modal.msgError("该货品已存在,可以直接修改已存在信息");
            return;
          }
        }
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const _names = row.name || names.value;
  proxy.$modal.confirm('是否确认删除货品"' + _names + '"？').then(function() {
    return delProduct(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('rawProduct/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

/** 格式化选择列表的货品编码 */
function formatterCode(item){
  return item.code + ' - ' + item.name;
}

/** 新增采购计划选择的货品编码改变时调用 */
function handleCodeSelectChange(value){
  rawProductList.value.forEach(item => {
    if(item.code === value){
      form.value.name = item.name;
    }
  })
}

initial();
</script>